package io.noties.markwon.app.samples.image;

import com.noties.markwon.utils.TextUtils;

import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonConfiguration;
import io.noties.markwon.app.sample.Tags;
import io.noties.markwon.app.sample.ui.MarkwonTextViewSample;
import io.noties.markwon.html.HtmlPlugin;
import io.noties.markwon.image.ImageSize;
import io.noties.markwon.image.ImageSizeResolverDef;
import io.noties.markwon.image.ImagesPlugin;
import io.noties.markwon.sample.annotations.MarkwonArtifact;
import io.noties.markwon.sample.annotations.MarkwonSampleInfo;
import ohos.agp.window.service.DisplayManager;

@MarkwonSampleInfo(
        id = "20210201165512",
        title = "ImageSizeResolver",
        description = "Custom `ImageSizeResolver` that treats dimension values " +
                "as density-based (like `dp`, `dip` in resources)",
        artifacts = {MarkwonArtifact.CORE},
        tags = {Tags.image}
)
public class ImageSizeResolverSample extends MarkwonTextViewSample {
    String image = TextUtils.getHttps()+"github.com/dcurtis/markdown-mark/raw/master/png/208x128-solid.png";
    private final String md = "  **150px x 150px**: <img src=\"$image\" width=\"150px\" height=\"150px\" alt=\"150px x 150px\" />\n" +
            "      \n" +
            "      **150 x 150**: <img src=\"$image\" width=\"150\" height=\"150\" alt=\"150 x 150\" />\n" +
            "      \n" +
            "      **no dimension**: <img src=\"$image\" alt=\"no dimension\" />\n" +
            "      \n" +
            "      **just width 150**: <img src=\"$image\" width=\"150\" alt=\"150\" />";

    @Override
    public void render() {
        Markwon markwon = Markwon.builder(context)
                .usePlugin(new AbstractMarkwonPlugin() {
                    @Override
                    public void configureConfiguration(MarkwonConfiguration.Builder builder) {
                        super.configureConfiguration(builder);
                        builder.imageSizeResolver(new DensityImageSizeResolver());
                    }
                })
                .usePlugin(ImagesPlugin.create())
                .usePlugin(HtmlPlugin.create())
                .build();
        markwon.setMarkdown(textView, md);
    }

    private class DensityImageSizeResolver extends ImageSizeResolverDef {
        final float density = DisplayManager.getInstance().getDefaultDisplay(context).get().getAttributes().scalDensity;

        @Override
        protected int resolveAbsolute(ImageSize.Dimension dimension, int original, float textSize) {
            if (dimension.unit == null) {
                // assume density pixels
                return (int) (dimension.value * density + 0.5F);
            }
            return super.resolveAbsolute(dimension, original, textSize);
        }
    }
}
